import base64
import os

from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.models import OauthQQUser, OAuthSinaUser
from oauth.utils import OAuthQQ, OAuthWB
from users.models import User


class QQAuthUserserializer(serializers.ModelSerializer):
    access_token = serializers.CharField(label='加密openid',write_only=True)
    mobile = serializers.RegexField(label='手机号',regex=r'^1[3-9]\d{9}$',write_only=True)
    sms_code = serializers.CharField(label='短信验证码',write_only=True)
    token = serializers.CharField(label='jwt token', read_only=True)

    class Meta:
        model = User
        fields = ['id','username','password','mobile','sms_code','access_token','token']
        extra_kwargs = {
            'username':{
                'read_only':True
            },
            'password':{
                'write_only':True
            }
        }

    # 手机号格式，短信验证码是否正确，access_token是否有效
    def validate(self, attrs):
        # 1 短信验证码验证
        sms_code = attrs['sms_code']
        # 验证短信验证码正确性
        # 链接redis2号库名verify_codes生成redis对象
        redis_conn = get_redis_connection('verify_codes')
        # 取出用户的手机号 和验证码
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        # 　从ｒｅｄｉｓ中取出真验证码
        sms_code_real = redis_conn.get('sms_code_%s' % mobile)  # 可能为None|bytes， 所以不能在这解码
        # 短信验证码可能会失效
        if not sms_code_real:
            raise serializers.ValidationError('短信验证码已过期')
        # 判断验证码是正确
        if sms_code != sms_code_real.decode():
            raise serializers.ValidationError('验证码输入错误')

        # 2 验证呢个access_token是否有效
        access_token = attrs['access_token']
        oauth = OAuthQQ()
        openid = oauth.check_save_user_token(access_token)
        if openid is None:
            raise serializers.ValidationError('获取access_token失败')
        attrs['openid'] = openid

        # 3 判断用户是否注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = None # 未注册
        else:
            # 如果已经注册,校验密码正确性
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
        attrs['user'] = user

        return attrs

    # 保存用户数据
    def create(self, validated_data):
        user = validated_data['user']

        if user is None:
            # 创建一个用户
            mobile = validated_data['mobile']
            # 随机生成用户名
            username = base64.b64encode(os.urandom(9)).decode()
            password = validated_data['password']
            user = User.objects.create_user(username=username,password=password,mobile=mobile)

        # 给类视图的对象增加属性user，保存绑定用户对象
        self.context['view'].user = user

        # 如果用户注册了,绑定用户qq
        # 保存QQ绑定的数据
        openid = validated_data['openid']
        OauthQQUser.objects.create(openid = openid,user = user)

        # 用户创建成功,注册成功后给客户端一个token,直接记录其身份证,然后下次就可以不用输入用户名密码了
        # 手动签发JWT token的值
        from rest_framework_jwt.settings import api_settings
        # 指定生成payload的方法,pyload可以自定义,但是这个里值返回token值
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 生成payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 给user对象属性一个token属性
        user.token = token

        return user



class WBAuthUserserializer(serializers.ModelSerializer):
    access_token = serializers.CharField(label='加密openid',write_only=True)
    mobile = serializers.RegexField(label='手机号',regex=r'^1[3-9]\d{9}$',write_only=True)
    sms_code = serializers.CharField(label='短信验证码',write_only=True)
    token = serializers.CharField(label='jwt token', read_only=True)

    class Meta:
        model = User
        fields = ['id','username','password','mobile','sms_code','access_token','token']
        extra_kwargs = {
            'username':{
                'read_only':True
            },
            'password':{
                'write_only':True
            }
        }

    # 手机号格式，短信验证码是否正确, access_token是否有效
    def validate(self, attrs):
        # 1 短信验证码验证
        sms_code = attrs['sms_code']
        # 验证短信验证码正确性
        # 链接redis2号库名verify_codes生成redis对象
        redis_conn = get_redis_connection('verify_codes')
        # 取出用户的手机号 和验证码
        mobile = attrs.get('mobile')
        sms_code = attrs.get('sms_code')
        # 　从ｒｅｄｉｓ中取出真验证码
        sms_code_real = redis_conn.get('sms_code_%s' % mobile)  # 可能为None|bytes， 所以不能在这解码
        # 短信验证码可能会失效
        if not sms_code_real:
            raise serializers.ValidationError('短信验证码已过期')
        # 判断验证码是正确
        if sms_code != sms_code_real.decode():
            raise serializers.ValidationError('验证码输入错误')

        # 2 验证access_token是否有效
        access_token = attrs['access_token']
        oauth = OAuthWB()
        access_token = oauth.check_save_user_token(access_token)
        if access_token is None:
            raise serializers.ValidationError('获取access_token失败')
        attrs['access_token'] = access_token

        # 3 判断用户是否注册
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = None # 未注册
        else:
            # 如果已经注册,校验密码正确性
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
        attrs['user'] = user

        return attrs

    # 保存用户数据
    def create(self, validated_data):
        user = validated_data['user']

        if user is None:
            # 创建一个用户
            mobile = validated_data['mobile']
            # 随机生成用户名
            username = base64.b64encode(os.urandom(9)).decode()
            password = validated_data['password']
            user = User.objects.create_user(username=username,password=password,mobile=mobile)

        # 给类视图的对象增加属性user，保存绑定用户对象
        self.context['view'].user = user

        # 如果用户注册了,绑定用户qq
        # 保存QQ绑定的数据
        access_token = validated_data['access_token']
        OAuthSinaUser.objects.create(access_token = access_token,user = user)

        # 用户创建成功,注册成功后给客户端一个token,直接记录其身份证,然后下次就可以不用输入用户名密码了
        # 手动签发JWT token的值
        from rest_framework_jwt.settings import api_settings
        # 指定生成payload的方法,pyload可以自定义,但是这个里值返回token值
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 生成payload
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 给user对象属性一个token属性
        user.token = token

        return user




